package com.slfx.open.api.controller;


import com.slfx.open.api.entity.ShortUrl;
import com.slfx.open.api.service.ShortUrlService;
import com.slfx.open.api.utils.AesHutoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * @author zengqingfa
 * @className ShortUrlController
 * @description
 * @create 2022/9/25 16:42
 */
@RestController
@Slf4j
@RequestMapping("/shortUrl")
public class ShortUrlController {

    @Resource
    private ShortUrlService shortUrlService;

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public ShortUrl getById(@RequestParam("id") Long id) {
        ShortUrl shortUrl = shortUrlService.getById(id);
        return shortUrl;
    }


    private static final String url = "http://localhost:8081/shortUrl/public/getById";

    /**
     * 后台主动生成外网可以访问的链接，携带加密的参数
     *
     * @param id
     * @return
     */
    @GetMapping("/getLinkUrl")
    public String getLinkUrl(@RequestParam("id") Long id) {
        ShortUrl shortUrl = shortUrlService.getById(id);
        if (shortUrl == null) {
            throw new RuntimeException("数据不存在");
        }
        //加密id
        String s = AesHutoolUtils.encryptHex(String.valueOf(id));
        StringBuilder builder = new StringBuilder(url).append("?id=" + s);
        return builder.toString();
    }

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    @GetMapping("/public/getById")
    public ShortUrl publicGetById(@RequestParam("id") String id) {
        //解密
        String s;
        try {
            s = AesHutoolUtils.decryptStr(id);
        } catch (Exception e) {
            log.error("参数非法,无权限访问! id={}", id);
            throw new RuntimeException("参数非法,无权限访问! ");
        }
        ShortUrl shortUrl = shortUrlService.getById(Long.valueOf(s));
        return shortUrl;
    }

}